package com.hanlyjiang.library.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.os.EnvironmentCompat;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Android 相关静态工具函数
 * Created by jianghanghang on 2016/9/28.
 */
public class AndroidUtils {

    private static final String SECONDARY_STORAGE = "SECONDARY_STORAGE";


    /**
     * 获取Uri中file的真实路径 适用性有限 请看源码
     *
     * @param contentResolver
     * @param data
     * @return
     */
    public static String getRealFilePathFromUri(ContentResolver contentResolver, Uri data) {
        if (data == null)
            return null;
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = contentResolver.query(data, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        //picturePath就是图片在储存卡所在的位置
        final String filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     * @author paulburke
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static boolean isLocalStorageDocument(Uri uri) {
        return LocalStorageProvider.AUTHORITY.equals(uri.getAuthority());
    }

    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                if (true)
                    DatabaseUtils.dumpCursor(cursor);

                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // LocalStorageProvider
            if (isLocalStorageDocument(uri)) {
                // The path is the id
                return DocumentsContract.getDocumentId(uri);
            }
            // ExternalStorageProvider
            else if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public void getBitmapByInputstream(ContentResolver contentResolver, Uri data) {
        try {
            InputStream is = contentResolver.openInputStream(data);
            Bitmap bitmap = BitmapFactory.decodeStream(is);

            File file = new File(Environment.getExternalStorageDirectory() + "bitmapfile");
            if (!file.exists()) {
                file.mkdir();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取对应Context的数据路径，一般是【主存储目录/包名】
     *
     * @param context context 对象
     * @return 应用主目录
     */
    public static String getDataHomeDir(Context context) {
        String packageName = context.getPackageName();
        File data = new File(Environment.getExternalStorageDirectory(), packageName);
        if (!data.exists()) {
            data.mkdirs();
        }
        return data.getAbsolutePath();
    }

    /**
     * 外部存储是否有挂载，如果没有外部存储，那么返回false
     *
     * @return false - 没有外部存储 / 没有挂载 / 不支持
     */
    public static boolean isExtSdMounted() {
        if (!AndroidUtils.isSupportEXTSD())
            return false;
        String secondaryStorage = AndroidUtils.getSECONDARY_STORAGE();
        if (secondaryStorage == null) {
            return false;
        }
        String state = EnvironmentCompat.getStorageState(new File(secondaryStorage));

        System.out.println(secondaryStorage + " : " + state);

        if (state.equals(Environment.MEDIA_MOUNTED)
                || AndroidUtils.isDirExists(secondaryStorage)) {
            System.out.println("mounted");
            return true;
        } else {
            if (new File(secondaryStorage).isDirectory()) {
                System.out.println("外部sd卡未挂载");
            }
            return false;
        }
    }

    /**
     * 是否支持外部第二存储,仅仅只是判断支持，不保证有挂载
     *
     * @return
     */
    public static boolean isSupportEXTSD() {
        return System.getenv("SECONDARY_STORAGE") == null ? false : true;
    }

    /**
     * 是否支持外部第二存储,仅仅只是判断支持，不保证有挂载
     *
     * @return null -不支持
     */
    public static String getSECONDARY_STORAGE() {
        String env = System.getenv("SECONDARY_STORAGE");
        if (env == null) {
            return env;
        } else {
            return env.split(":")[0];
        }
    }

    /**
     * 路径在文件系统中是否事实存在
     *
     * @param path
     * @return
     */
    public static boolean isDirExists(String path) {
        if (!new File(path).isDirectory()) {
            return false;
        }
        if (new File(path).listFiles() == null) {
            return false;
        }
        if (new File(path).listFiles().length <= 0) {
            return false;
        }
        return true;
    }

    /**
     * 通过类名启动Activity包装
     *
     * @param activity  当前Activity引用
     * @param className 要启动的Activity类名
     */
    public static void startActivityByClassName(Activity activity, String className) {
        Intent intent = new Intent();
        intent.setClassName(activity, className);
        activity.startActivity(intent);
    }

    /**
     * 以 Toast.LENGTH_SHORT 的时长显示toast，内容为 msg
     *
     * @param context Context
     * @param msg     要显示的内容
     */
    public static void showToast(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * /**
     * 以 Toast.LENGTH_SHORT 的时长显示toast，内容为 msg
     *
     * @param context  Context
     * @param msgResId String id
     */
    public static void showToast(Context context, int msgResId) {
        Toast.makeText(context, context.getResources().getString(msgResId), Toast.LENGTH_SHORT).show();
    }

    /**
     * 显示默认效果的对话框，带确定和取消两个按钮
     *
     * @param context     Context
     * @param title       标题
     * @param msg         对话框主体内容
     * @param okClick     确定按钮点击事件
     * @param cancelClick 取消按钮点击事件
     */
    public static void showDialog(Context context, String title, String msg,
                                  DialogInterface.OnClickListener okClick,
                                  DialogInterface.OnClickListener cancelClick) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(msg);
        builder.setNegativeButton("取消", cancelClick);
        builder.setPositiveButton("确定", okClick);
        builder.create().show();
    }


    /**
     * 显示默认等待对话框的创建
     *
     * @param context Context对象
     * @param title   标题
     * @param msg     对话框主体内容
     * @return 改对话框的引用，用于关闭该对话框
     */
    public static ProgressDialog showWaitDialog(Context context, String title, String msg) {
        return ProgressDialog.show(context, title, msg);
    }

    /**
     * 获取当前程序的版本名称
     *
     * @param context Context
     * @return 版本名称
     * @throws PackageManager.NameNotFoundException
     */
    public static String getVersionName(Context context) throws PackageManager.NameNotFoundException {
        //获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        return packInfo.versionName;
    }

    /**
     * 获取当前程序的版本号
     *
     * @param context Context
     * @return 版本号
     * @throws Exception
     */
    public static int getVersionNumber(Context context) throws PackageManager.NameNotFoundException {
        //获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        return packInfo.versionCode;
    }

}
